<template>
  <div class="settle-manage">
    <div style="margin-bottom: 20px;">
      <el-button type="primary" @click="handleAdd" :disabled="displayAddBtnFlag">添加分组</el-button>
    </div>
    <el-table :data="sourceData.list" highlight-current-row stripe row-key="id"
      @expand-change="handleExpandChange" :show-header="false" max-height="700">
      <el-table-column type="selection" width="40" />
      <el-table-column type="expand" width="40">
        <template #default="{ row }">
          <div class="expand-content" style="padding: 20px;">
            <el-table :data="row.group" border>
              <el-table-column label="水表名称" prop="equipName" />
              <el-table-column label="水表编号" prop="equipNum" min-width="150" />
              <el-table-column label="当前账期" prop="currentBillPeriod" />
              <el-table-column label="当前用量(t)" prop="currentUsage" />
              <el-table-column label="上期用量(t)" prop="previousUsage" />
              <el-table-column label="水表位置" prop="location" />
              <el-table-column label="操作" align="center" width="160">
                <template #default="{ row: childRow }">
                  <el-button type="danger" link @click="removeEquipUsage(childRow)">解绑水表</el-button>
                  <el-button type="danger" link @click="editEquipUsage(childRow)">编辑用量</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="组名">
        <template #default="{ row }">
          <span>{{ row.groupName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分组编码">
        <template #default="{ row }">
          <span>编号：{{ row.groupCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用途">
        <template #default="{ row }">
          <span>用途：{{ row.usage }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计费单价">
        <template #default="{ row }">
          <span>单价：{{ row.unitPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="比例">
        <template #default="{ row }">
          <span>分摊比例：{{ row.allocationRatio }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
          <el-button type="primary" link @click="handleBind(row)">
            绑定水表
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <GroupInfoDialog ref="dialog" @listChange="getList" />
  <EquipSelectDialog ref="equipSelectDialog" @confirm="handleBindSuccess" />
  <EquipUsageUpdateDialog ref="equipUsageUpdateDialog" @listChange="handleEditEquipUsageSuccess" />
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import GroupInfoDialog from "./GroupInfoDialog.vue";
import EquipSelectDialog from "./EquipSelectDialog.vue";
import EquipUsageUpdateDialog from './EquipUsageUpdateDialog.vue'
import { getGroupListByEnterprise, deleteGroup, deleteEquipUsage, getEquipUsageListByGroupId } from '@/api/settle'
import type { MrsGroupQueryByCodeRequest, MrsGroup } from '@/api/types/rent'
import type { MrsEquipUsageQueryRequest } from '@/api/types/equipUsage'

const sourceData = reactive({
  list: [] as any,
})

const displayAddBtnFlag = ref(true)
const enterpriseId = ref(null)
const tenantId = ref(null)
// 地点位置管理对话框
const equipSelectDialog: any = ref(null)
// 当前分组对象
const currentGroup = ref(null)

// 监听企业ID变化
watch(() => enterpriseId.value, (newEnterpriseId) => {
  if (newEnterpriseId) {
    displayAddBtnFlag.value = false
  }
}, { immediate: true })

// 处理展开行变化
const handleExpandChange = async (row: any, expandedRowsData: any[]) => {
  const rowKey = row.id || row.groupName
  const isExpanding = expandedRowsData.some(item => (item.id || item.groupName) === rowKey)
  if (isExpanding) {
    // 展开
    // 展开时获取该分组的水表详情
    if (row.id) {
      currentGroup.value = row
      await loadGroupEquipUsageDetails(row)
    }
  }
}

// 加载分组的水表详情
const loadGroupEquipUsageDetails = async (groupRow: any) => {
  try {
    console.log(`正在加载分组 ${groupRow.groupName}(分组ID: ${groupRow.id}) 的水表详情...`)
    const queryData: MrsEquipUsageQueryRequest = {
      equipType: 2,
      groupId: groupRow.id
    }
    const response = await getEquipUsageListByGroupId(queryData)
    if (response.success && response.data) {
      // 更新对应分组的水表详情
      const groupIndex = sourceData.list.findIndex((group: any) => (group.id || group.groupName) === (groupRow.id || groupRow.groupName))
      if (groupIndex > -1) {
        sourceData.list[groupIndex].group = response.data
      }
    } else {
      ElMessage.warning(`获取分组"${groupRow.groupName}"的水表详情失败`)
    }
  } catch (error: any) {
    ElMessage.error(`加载分组"${groupRow.groupName}"的水表详情失败: ${error.message || '未知错误'}`)
  }
}

// 解绑水表
const removeEquipUsage = async (childRow: any) => {
  await ElMessageBox.confirm(
      `确定解绑该水表："${childRow.equipName}"吗？`,
      "解绑水表确认",
      {
        confirmButtonText: "确定解绑",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
      },
    );
  try {
    const response = await deleteEquipUsage(childRow.id)
    if (response.success) {
      ElMessage.success('水表解绑成功！')
      await loadGroupEquipUsageDetails(currentGroup.value) // 刷新列表
    } else {
      ElMessage.error('水表解绑失败：' + (response.msg || '未知错误'))
    }
  } catch (error: any) {
    ElMessage.error('解绑水表失败，请稍后重试')
  }
}

// 编辑设备用量信息弹窗对象
const equipUsageUpdateDialog: any = ref(null)
const editEquipUsage = (childRow: any) => {
  let equipUsageUpdateDialogObj = equipUsageUpdateDialog.value
  equipUsageUpdateDialogObj.dialogVisible = true
  equipUsageUpdateDialogObj.dialogTitle = '编辑水表用量信息'
  let tableItem = equipUsageUpdateDialogObj.tableItem
  tableItem.id = childRow.id
  tableItem.settleDate = ''
  tableItem.currentUsage = childRow.currentUsage
  tableItem.previousUsage = childRow.previousUsage
  tableItem.enterpriseId = childRow.enterpriseId
  tableItem.usageUnit = 't'
}
const handleEditEquipUsageSuccess = () => {
  loadGroupEquipUsageDetails(currentGroup.value)
}

const handleBind = (row: any) => {
  console.log('打开地点位置管理，选择水表绑定到分组:', row)
  
  // 检查分组基本信息是否完整
  if (!row.groupName || !row.groupCode || !row.usage || !row.unitPrice || !row.allocationRatio) {
    ElMessage.error('分组信息不完整，请先完善分组配置！')
    return
  }
    
  // 打开地点位置管理对话框，传递水表绑定类型
  equipSelectDialog.value.openDialog(tenantId.value, 2, row.id, enterpriseId.value)
}

const handleBindSuccess = () => {
  ElMessage.success('添加水表成功！')
  loadGroupEquipUsageDetails(currentGroup.value) // 刷新列表
}

// 获取分组列表数据（使用真实API）
const getList = async () => {
  try {
    // 如果没有企业ID，显示空列表
    if (!enterpriseId.value) {
      console.log('没有选中企业，显示空列表')
      sourceData.list = []
      return
    }

    // 构建查询参数
    const queryData: MrsGroupQueryByCodeRequest = {
      enterpriseId: Number(enterpriseId.value), // 企业ID
      objectType: '水表' // 只查询水表类型的分组
    }

    // 获取企业的所有分组
    const response = await getGroupListByEnterprise(queryData)
    await handleGroupListResponse(response)
  } catch (error: any) {
    sourceData.list = []
    ElMessage.error(`获取分组列表失败: ${error.message || '未知错误'}`)
  }
}

// 处理分组列表API响应
const handleGroupListResponse = async (response: any) => {
  if (response.success && response.data) {
    // 转换数据格式以适配现有组件结构
    const transformedData = response.data.map((group: MrsGroup) => ({
      id: group.id,
      groupName: group.groupName,
      groupCode: group.groupCode || '',
      usage: group.usageType === 1 ? '公摊' : '自用',
      unitPrice: `${group.unitPrice || 0}元/t`,
      allocationRatio: `${group.allocationRatio || 0}%`,
      group: [] // 点击展开时会动态加载
    }))

    sourceData.list = transformedData
    console.log(`已加载分组数据，共 ${transformedData.length} 条记录`)
  } else {
    sourceData.list = []
    if (response.msg) {
      ElMessage.warning(`获取分组列表失败: ${response.msg}`)
    }
  }
}

onMounted(() => {
  getList()
})

const dialog: any = ref(null)

// 添加水表
const handleAdd = () => {
  console.log("当前企业ID:", enterpriseId.value)
  dialog.value.dialogVisible = true
  dialog.value.dialogStatus = 'create'
  dialog.value.isDisabled = true
  dialog.value.groupId = ''
  dialog.value.unitPriceLabel = '元/t'
  dialog.value.objectType = '水表'

  // 重置表单数据
  dialog.value.reset()

  // 生成默认分组编码
  const timestamp = Date.now().toString().slice(-6)
  dialog.value.tableItem.groupCode = `R${timestamp}`

  // 设置默认值 - 适配水表字段
  dialog.value.tableItem.usage = '自用'
  dialog.value.tableItem.unitPrice = 0.85
  dialog.value.tableItem.allocationRatio = 100.0

  // 设置企业ID
  if (dialog.value.setEnterpriseId) {
    dialog.value.setEnterpriseId(enterpriseId.value)
  }
}

// 编辑水表
const handleEdit = (row: any) => {
  dialog.value.dialogVisible = true
  dialog.value.dialogStatus = 'edit'
  dialog.value.isDisabled = true
  dialog.value.groupId = row.id
  dialog.value.unitPriceLabel = '元/t'
  dialog.value.objectType = '水表'

  // 重置表单数据
  dialog.value.reset()

  // 填充表单数据 - 适配水表字段
  Object.assign(dialog.value.tableItem, {
    groupName: row.groupName, 
    groupCode: row.groupCode,
    usage: row.usage,
    unitPrice: parseFloat(row.unitPrice.replace('元/度', '')), // 从显示格式中提取数字
    allocationRatio: parseFloat(row.allocationRatio.replace('%', '')), // 从显示格式中提取数字
  })
  
  // 设置企业ID
  if (dialog.value.setEnterpriseId) {
    dialog.value.setEnterpriseId(enterpriseId.value)
  }
}

// 删除单个水表分组
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除水表分组："${row.groupName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await deleteGroup(row.id)
    if (response.success) {
      ElMessage.success('分组删除成功！')
      await getList() // 刷新列表
    } else {
      ElMessage.error('分组删除失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    } else {
      ElMessage.info('已取消删除')
    }
  }
}

defineExpose({ getList, enterpriseId, tenantId });
</script>

<style lang="scss" scoped>
.expand-content {
  background-color: #f8f9fa;
  border-radius: 4px;
  margin: 10px 0;

  .el-table {
    margin: 0;

    // 移除嵌套表格的竖线边框
    :deep(.el-table__cell) {
      border-right: none !important;
    }

    :deep(.el-table__border-left-patch) {
      display: none;
    }

    :deep(.el-table__fixed-right-patch) {
      display: none;
    }
  }
}

// 移除主表格的竖线边框
:deep(.el-table .el-table__cell) {
  border-right: none !important;
}

:deep(.el-table__border-left-patch) {
  display: none;
}

:deep(.el-table__fixed-right-patch) {
  display: none;
}
</style>